package ysq.xyg.base.util;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;

/**
 * @author yu sheng qiang
 * @create 2017-03-22 16:43
 **/
public final class BaseUtil {
    //获取id
    public static  String uId(){
        return  DateUtil.format(new Date(),BaseConstant.DATE_TIME_PATTERN_2)+RandomUtil.randomNumbers(14);
    }
    //首字母转小写
    public static String toLowerCaseFirstOne(String s){
        if(Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    //驼峰命名如：sys_user => sysUser
    public static String toTfmm(String str){
        String[] columList=str.split("_");
        StringBuffer s=new StringBuffer();
        if(columList!=null&&columList.length>0){
            for(int i=0;i<columList.length;i++){
                if(i==0){
                    s.append(columList[i]);
                }else{
                    s.append(BaseUtil.toUpperCaseFirstOne(columList[i]));
                }
            }
        }
        return s.toString();
    }
    //首字母转大写
    public static String toUpperCaseFirstOne(String s){
        if(Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    /**
     * 是否包含字符串
     *
     * @param str 验证字符串
     * @param strs 字符串组
     * @return 包含返回true
     */
    public static boolean inStringIgnoreCase(String str, String... strs)
    {
        if (str != null && strs != null)
        {
            for (String s : strs)
            {
                if (str.equalsIgnoreCase(trim(s)))
                {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 将下划线大写方式命名的字符串转换为驼峰式。如果转换前的下划线大写方式命名的字符串为空，则返回空字符串。 例如：HELLO_WORLD->HelloWorld
     *
     * @param name 转换前的下划线大写方式命名的字符串
     * @return 转换后的驼峰式命名的字符串
     */
    public static String convertToCamelCase(String name)
    {
        StringBuilder result = new StringBuilder();
        // 快速检查
        if (name == null || name.isEmpty())
        {
            // 没必要转换
            return "";
        }
        else if (!name.contains("_"))
        {
            // 不含下划线，仅将首字母大写
            return name.substring(0, 1).toUpperCase() + name.substring(1);
        }
        // 用下划线将原始字符串分割
        String[] camels = name.split("_");
        for (String camel : camels)
        {
            // 跳过原始字符串中开头、结尾的下换线或双重下划线
            if (camel.isEmpty())
            {
                continue;
            }
            // 首字母大写
            result.append(camel.substring(0, 1).toUpperCase());
            result.append(camel.substring(1).toLowerCase());
        }
        return result.toString();
    }
    /**
     * 去空格
     */
    public static String trim(String str)
    {
        return (str == null ? "" : str.trim());
    }

    public static HttpServletRequest getRequest()
    {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

        return request;
    }

    //获取文件名称
    public static String acceptFileName(String fileType){
        String  fileName = DateUtil.format(new Date(),BaseConstant.DATE_TIME_PATTERN_2)+ RandomUtil.randomNumbers(6)+"."+fileType;
        return fileName;
    }

    //获取文件目录
    public static String acceptFileDir(String realPath,String dir){
        //如果文件夹不存在则创建
        File dicFile =new File(realPath,dir);
        if(!dicFile .exists()  && !dicFile .isDirectory()){
            dicFile .mkdirs();
        }
        return dicFile.getAbsolutePath();
    }

    //获取文件的后缀
    public static String acceptFileType(String fileName){
        String suffix = fileName.indexOf(".")!=-1?fileName.substring(fileName.lastIndexOf(".")+1, fileName.length()):null;
        return suffix;
    }
    //判断是否是图片
    public static boolean fileCheckImg(String type){
        if(!StrUtil.isEmpty(type)&&(type.equalsIgnoreCase("jpg")||type.equalsIgnoreCase("jpeg")||type.equalsIgnoreCase("gif")||type.equalsIgnoreCase("png"))){
            return true;
        }
        return false;
    }
    //判断是否是execl
    public static boolean fileCheckExecl(String type){
        if(!StrUtil.isEmpty(type)&&(type.equalsIgnoreCase("xls")||type.equalsIgnoreCase("xlsx"))){
            return true;
        }
        return false;
    }
    /**
     * Base64 解码
     * @param name
     * @return
     */
    public static String decodeBase64(String name){
        try {
            return new String(Base64.decodeBase64(name),"UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * Base64 编码
     * @param name
     * @return
     */
    public static String encodeBase64String(String name){
        try {
            return Base64.encodeBase64String(name.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * url的处理
     * @param str
     * @return
     */
    public static String urlEnodeUTF8(String str){
        String result = str;
        try {
            result = URLEncoder.encode(str,"UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据身份证获取年龄
     * @param certId
     * @return
     */
    public static int getAgeByCertId(String certId) throws ParseException {
        String birthday = "";
        if (certId.length() == 18) {
            birthday = certId.substring(6, 10) + "/"
                    + certId.substring(10, 12) + "/"
                    + certId.substring(12, 14);
        }else{
            return 0;
        }
        Date now = new Date();
        Date birth = ysq.xyg.base.util.DateUtil.getTextDate(birthday,"yyyy/MM/dd");
        long intervalMilli = now.getTime() - birth.getTime();
        if(intervalMilli<=0){
            return 0;
        }
        int age = (int) (intervalMilli/(24 * 60 * 60 * 1000))/365;
        return age;
    }
    /**
     * 根据生日获取年龄
     * @return
     */
    public static int getAgeByBrithday(String brithday) throws ParseException {

        Date now = new Date();
        Date birth = ysq.xyg.base.util.DateUtil.getTextDate(brithday,"yyyy-MM-dd");
        long intervalMilli = now.getTime() - birth.getTime();
        if(intervalMilli<=0){
            return 0;
        }
        int age = (int) (intervalMilli/(24 * 60 * 60 * 1000))/365;
        return age;
    }

}
